<template>
  <div class="training-list">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>创新创业培训</span>
          <el-button type="primary" @click="showMyRegistration">报名记录</el-button>
        </div>
      </template>
      <el-table :data="trainingList" style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="培训主题" min-width="200" />

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 培训详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentTraining?.title"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-if="currentTraining" class="training-detail" v-html="currentTraining.content"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMyRegistration">查看我的报名</el-button>
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="showRegisterDialog">立即报名</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 报名表单弹窗 -->
    <el-dialog
      v-model="registerDialogVisible"
      title="培训报名"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="联系信息" prop="contactInfo">
          <el-input v-model="form.contactInfo" placeholder="请输入联系信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="registerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRegister">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 报名记录弹窗 -->
    <el-dialog
      v-model="registrationDialogVisible"
      title="我的报名记录"
      width="70%"
      :close-on-click-modal="false"
    >
      <el-table :data="registrationList" style="width: 100%" v-loading="registrationLoading">
        <el-table-column prop="name" label="培训主题" min-width="200" />
        <el-table-column prop="contactInfo" label="联系信息" width="150" />
        <el-table-column prop="createTime" label="报名时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getRegistrationStatusType(row.status)">
              {{ getRegistrationStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 报名记录分页 -->
      <div class="registration-pagination-container">
        <el-pagination
          v-model:current-page="registrationCurrentPage"
          v-model:page-size="registrationPageSize"
          :page-sizes="[5, 10, 20, 30]"
          :total="registrationTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleRegistrationSizeChange"
          @current-change="handleRegistrationCurrentChange"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="registrationDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { attendEnterpriseActivity, getAttendEnterpriseActivity, listEnterpriseActivity } from '@/api/enterpeise';
import { getAnnouncementList } from '@/api/park';
import {useUserStore} from '@/store/user'

const router = useRouter();
const formRef = ref<FormInstance>();
const {userInfo} = useUserStore()

// 表单数据
const form = reactive({
  contactInfo: '',
});

// 表单验证规则
const rules = reactive<FormRules>({
  contactInfo: [
    { required: true, message: '请输入联系信息', trigger: 'blur' },
    { max: 200, message: '不能超过200字', trigger: 'blur' },
  ],
});

// 培训列表数据
const loading = ref(false);
const trainingList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 详情对话框
const dialogVisible = ref(false);
const currentTraining = ref(null);

// 报名表单弹窗
const registerDialogVisible = ref(false);

// 报名记录弹窗
const registrationDialogVisible = ref(false);
const registrationList = ref([]);
const registrationLoading = ref(false);
// 报名记录分页数据
const registrationCurrentPage = ref(1);
const registrationPageSize = ref(5);
const registrationTotal = ref(0);

// 获取培训列表
const getTrainingList = async () => {
  loading.value = true;
  try {
    // TODO: 调用获取培训列表的API
    const res = await getAnnouncementList({
      current: currentPage.value,
      size: pageSize.value,
      type: 8
    });
    trainingList.value = res.data.records;
    total.value = res.data.total;

    // 模拟数据
    // trainingList.value = [
    //   {
    //     id: 1,
    //     title: '创新创业基础培训',
    //     time: '2024-05-01 09:00',
    //     location: '科技园A栋101',
    //     scale: 50,
    //     status: 'ongoing',
    //     content: `
    //       <div class="training-info">
    //         <h3>培训详情</h3>
    //         <p><strong>培训时间：</strong>2024-05-01 09:00</p>
    //         <p><strong>培训地点：</strong>科技园A栋101</p>
    //         <p><strong>培训规模：</strong>50人</p>
    //         <p><strong>主办单位：</strong>桂林电子科技大学科技园</p>
    //         <p><strong>培训对象：</strong>在校学生、教师</p>

    //         <h3>培训内容</h3>
    //         <p>创新创业基础知识培训，包括创业思维、商业模式、团队建设等内容。</p>

    //         <h3>培训日程</h3>
    //         <ul>
    //           <li>09:00-10:30 创业思维培养</li>
    //           <li>10:45-12:00 商业模式设计</li>
    //           <li>14:00-15:30 团队建设与管理</li>
    //           <li>15:45-17:00 案例分析</li>
    //         </ul>

    //         <h3>注意事项</h3>
    //         <p>请提前15分钟到场签到，自备笔记本和笔。</p>
    //       </div>
    //     `
    //   }
    // ];
    // total.value = 1;
  } catch (error) {
    ElMessage.error('获取培训列表失败');
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getTrainingList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getTrainingList();
};

// 报名记录分页处理
const handleRegistrationSizeChange = (val: number) => {
  registrationPageSize.value = val;
  getMyRegistration();
};

const handleRegistrationCurrentChange = (val: number) => {
  registrationCurrentPage.value = val;
  getMyRegistration();
};

// 状态处理
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'not_started': 'info',
    'ongoing': 'success',
    'ended': 'warning',
    'cancelled': 'danger'
  };
  return statusMap[status] || 'info';
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'not_started': '未开始',
    'ongoing': '进行中',
    'ended': '已结束',
    'cancelled': '已取消'
  };
  return statusMap[status] || '未知';
};

// 查看详情
const handleView = (row: any) => {
  currentTraining.value = row;
  dialogVisible.value = true;
};

// 显示报名表单
const showRegisterDialog = () => {
  registerDialogVisible.value = true;
  form.contactInfo = '';
};

// 报名
const handleRegister = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await attendEnterpriseActivity({
          activityId: currentTraining.value?.id,
          contactInfo: form.contactInfo,
          ActivityCode: 8
        });
        if(res.code === 200){
          ElMessage.success('报名成功');
          registerDialogVisible.value = false;
          dialogVisible.value = false;
        }else{
          ElMessage.error('报名失败');
        }
      } catch (error) {
        console.error('报名失败:', error);
        ElMessage.error('报名失败');
      }
    }
  });
};

// 获取我的报名信息
const getMyRegistration = async () => {
  registrationLoading.value = true;
  try {
    const res = await getAttendEnterpriseActivity({
      current: registrationCurrentPage.value,
      size: registrationPageSize.value,
      attendId: userInfo.userMsg.userId,
      type: 8
    });
    registrationList.value = res.data.records;
    registrationTotal.value = res.data.total;
  } catch (error) {
    console.error('获取报名信息失败:', error);
    ElMessage.error('获取报名信息失败');
  } finally {
    registrationLoading.value = false;
  }
};

// 显示报名记录
const showMyRegistration = () => {
  // 重置分页参数
  registrationCurrentPage.value = 1;
  registrationPageSize.value = 5;
  registrationDialogVisible.value = true;
  getMyRegistration();
};

// 报名状态处理
const getRegistrationStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': 'info',
    'approved': 'success',
    'rejected': 'danger'
  };
  return statusMap[status] || 'info';
};

const getRegistrationStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  };
  return statusMap[status] || '未知';
};

// 初始化
getTrainingList();
</script>

<style scoped lang="scss">
.training-list {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .training-detail {
    :deep(.training-info) {
      h3 {
        margin: 20px 0 10px;
        color: #409EFF;
      }

      p {
        margin: 10px 0;
        line-height: 1.6;
      }

      ul {
        margin: 10px 0;
        padding-left: 20px;

        li {
          margin: 5px 0;
          line-height: 1.6;
        }
      }
    }
  }

  .register-form {
    margin-top: 20px;
    max-width: 500px;
  }

  // 报名记录分页样式
  .registration-pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>